<?php
/*
* @Descripttion: 机器人相关类
* @Author: jiosen <4631458@qq.com>
* @Date: 2024-06-06 16:05:00
*/

namespace app\service;

use GuzzleHttp\Client;
use Exception;

class Bot
{   
    /**
     * 获取好友列表
     * @return array
     */
    static public function getFriendList()
    {
        $res = self::get('/get_friend_list');

        return $res['state'] == 1 ? $res['data'] : []; 
    }
    /**
     * 获取好友数量
     * @return int
     */
    static public function getFriendCount()
    {
        $list = self::getFriendList();

        return count($list);
    }

    /**
     * 获取群列表
     * @return array
     */
    static public function getGroupList()
    {
        $res = self::get('/get_group_list');

        return $res['state'] == 1 ? $res['data'] : []; 
    }
    /**
     * 获取群数量
     * @return int
     */
    static public function getGroupCount()
    {
        $list = self::getGroupList();

        return count($list);
    }
    /**
     * GET请求bot接口
     * @param string $api 请求地址
     * @param array $data 请求参数
     * @return array
     */
    static function get($api,$data=[])
    {
        return self::request('GET',$api,$data);
    }
    /**
     * POST请求bot接口
     * @param string $api 请求地址
     * @param array $data 请求参数
     * @return array
     */
    static function post($api,$data=[])
    {
        return self::request('POST',$api,$data);
    }
    /**
     * 请求bot接口
     * @param string $method 请求方式
     * @param string $api 请求地址
     * @param array $data 请求参数
     * @return array
     */
    static public function request($method,$api,$data=[])
    {
        $options = [];
        if($method == 'GET'){
            $options['query'] = $data;
        }else{
            $options['form_params'] = $data;
        }

        $res = ['state'=>0,'msg'=>'请求失败','data'=>[],'code'=>0];

        try{

            $client = new Client(['base_uri' => config('bot.host')]);

            $re = $client->request($method,$api,$options);
            
            if($re->getStatusCode() != 200){
                $res['msg'] = "网络异常:{$re->getStatusCode()}";
                $res['code'] = 404;
            }else{

                $re = json_decode($re->getBody(),true);

                if($re['retcode'] == 0 && $re['status'] == 'ok'){
                    $res = [
                        'state' => 1,
                        'msg' => '请求成功',
                        'data' => $re['data'],
                        'code'=>0
                    ];
                }else{
                    $res['msg'] = $re['message'];
                }
                
            }
            
            
        }catch(Exception $e){
            
        }

        return $res;
    }

    /**
     * 解析cq码
     * @param string $str
     * @return array
     */
    static public function parsCqCode($str)
    {
        // 正则表达式匹配cq码 [CQ:类型,参数=值,参数=值]
        $pattern = '/\[\CQ:(.*?)]/';

        preg_match_all($pattern, $str, $matches);

        $res = [];

        foreach($matches[1] as $value)
        {
            $arr = explode(',',$value);
            $type = array_shift($arr);

            $fields = [];

            foreach($arr as $v)
            {
                $field = explode("=",$v,2);
                $fields[$field[0]] = isset($field[1]) ? $field[1] : '';
            }

            $res[] = [
                'type' => $type,
                'data' => $fields
            ];
        }
        
        return $res;
    }

    /**
     *  是否艾特qq
     * @param mixed $data
     * @param int $qq
     * @param bool $cq
     * @return bool
     */
    static public function atQQ($data,$qq=0,$cq=true)
    {
        if($cq){
            $data = self::parsCqCode($data);
        }

        if(!is_array($data)){
            return false;
        }

        if(empty($qq)){
            $qq = self::getBotQQ();
        }

        $list = array_filter($data,function($item){
            return $item['type'] == 'at';
        });

        $re = false;

        foreach($list as $value)
        {
            if(!empty($value['data']['qq']) &&  $value['data']['qq'] == $qq){
                $re = true;
                break;
            }
        }

        return $re;
    }

    static public function getBotQQ()
    {
        // 获取登录信息
        $user = Bot::get('/get_login_info');

        return ($user['state'] == 1 && !empty($user['data']['user_id'])) ? $user['data']['user_id'] : 0 ;
    }
}